"""数据库模型"""

from datetime import datetime
from typing import Optional
from sqlalchemy import Column, Integer, String, DateTime, BigInteger, Index
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from nonebot import logger
from .config import config

Base = declarative_base()


class MessageRecord(Base):
    """消息记录表"""
    __tablename__ = "message_records"
    
    id = Column(Integer, primary_key=True, autoincrement=True)
    group_id = Column(String(20), nullable=False, comment="群组ID")
    user_id = Column(String(20), nullable=False, comment="用户ID")
    username = Column(String(50), nullable=True, comment="用户名")
    user_avatar = Column(String(500), nullable=True, comment="用户头像URL")
    group_name = Column(String(100), nullable=True, comment="群组名称")
    
    # 各时段消息计数
    today_count = Column(Integer, default=0, comment="今日消息数")
    yesterday_count = Column(Integer, default=0, comment="昨日消息数")
    week_count = Column(Integer, default=0, comment="本周消息数")
    month_count = Column(Integer, default=0, comment="本月消息数")
    year_count = Column(Integer, default=0, comment="今年消息数")
    total_count = Column(Integer, default=0, comment="总消息数")
    
    created_at = Column(DateTime, default=datetime.now, comment="创建时间")
    updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment="更新时间")
    
    # 创建复合索引
    __table_args__ = (
        Index('idx_group_user', 'group_id', 'user_id'),
        Index('idx_group_id', 'group_id'),
        Index('idx_user_id', 'user_id'),
    )


class ResetState(Base):
    """重置状态表"""
    __tablename__ = "reset_states"
    
    key = Column(String(50), primary_key=True, comment="状态键")
    last_reset = Column(DateTime, nullable=False, comment="上次重置时间")
    

class DatabaseManager:
    """数据库管理器"""
    
    def __init__(self):
        self.engine = None
        self.session_factory = None
        self._initialized = False
    
    def init_database(self, database_url: Optional[str] = None):
        """初始化数据库"""
        if self._initialized:
            return
            
        if database_url is None:
            database_url = config.message_counter_database_url or "sqlite:///message_counter.db"
        
        try:
            self.engine = create_engine(database_url, echo=False)
            Base.metadata.create_all(self.engine)
            self.session_factory = sessionmaker(bind=self.engine)
            self._initialized = True
            logger.info(f"数据库初始化成功: {database_url}")
        except Exception as e:
            logger.error(f"数据库初始化失败: {e}")
            raise
    
    def get_session(self):
        """获取数据库会话"""
        if not self._initialized:
            self.init_database()
        return self.session_factory()
    
    def close(self):
        """关闭数据库连接"""
        if self.engine:
            self.engine.dispose()
            self._initialized = False


# 全局数据库管理器实例
db_manager = DatabaseManager()


def get_db_session():
    """获取数据库会话的便捷函数"""
    return db_manager.get_session()


def init_db():
    """初始化数据库的便捷函数"""
    db_manager.init_database()